package com.project.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component    //标识该类是个spring组件类
@Aspect        //声明该类为切面类
public class ServiceAspect {
    //表示该方法在目标方法执行前会调用
    @Before("execution(* com.project.service..*.*(..))")
    public void beforeMethod(){
        System.out.println("这是一个前通知");


    }
    @After("execution(* com.project.service..*.*(..))")
//    @AfterReturning("execution(* com.project.service..*.*(..))")
    public void afterMethod(){
        System.out.println("这是一个后通知");
    }
    @Around("execution(* com.project.service..*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pj){
        try {
            System.out.println("环绕前");
            //执行目标方法，得到方法执行后的返回值
            Object returnObj = pj.proceed();
            //得到目标对象
            Object targetObj = pj.getTarget();
            System.out.println("环绕后");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
    @AfterThrowing(value = "execution(* com.project.service..*.*(..))",
            throwing = "e")  //throwing = "e" 表示目标方法抛出的异常由形参e接收
    public void throwException(JoinPoint jp,Exception e){
        //得到目标对象
        Object targetObj = jp.getTarget();
        //得到目标方法名
        String methodName = jp.getSignature().getName();

        System.out.println("执行"+targetObj.getClass().getName()+" 的 "+methodName+"()  方法抛出"+
                  e.getClass().getName());
    }

}
